/**
 * $Id: DealOverDateNeedReportMTThread.java,v 1.13 2006/10/30 08:39:37 martin Exp $
 *
 * Copyright 2006 Skyinfo, Inc. All Rights Reserved.
 */
package com.haoxi.gateway.runner.datadeal;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.haoxi.gateway.common.MTStatusAndReportBean;
import com.haoxi.gateway.common.SQLConst;
import com.haoxi.gateway.common.SYSConst;
import com.haoxi.gateway.runner.RunnerMgr;
import com.haoxi.gateway.runner.smscommand.SubmitReportCmd;
import com.haoxi.gateway.util.db.DBConnectUtil;
import com.haoxi.gateway.util.db.DealOracleDBUtil;

/**
 * 处理MTRespMap数据进行超时处理。
 * 
 * Revision History
 * 
 * 2006-5-31,star.Zhao,created it
 */
public class DealOverDateNeedReportMTThread implements Runnable {
    private final static Log log = LogFactory
            .getLog(DealOverDateNeedReportMTThread.class);
    
    private String name;
    /**
     * 定时检测时间
     */
    private int delay;

    private final static String OVERDATE_ERROR_INFO = "No_MTReport";
    /**
     * 运行
     */
    private boolean running = false;

    public DealOverDateNeedReportMTThread(int delay) {
        this.delay = delay;
        this.name = "DealOverDateNeedReportMTThread";
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Runnable#run()
     */
    public void run() {
        running = true;
        while (running) {
            /**
             * 需要的数据库名
             */
            Map systemConf = RunnerMgr.getInstance().getSystemConf();
            String gateway_history = (String)systemConf.get(SYSConst.CONF_DB_HISTORY) ;
            String gateway_DBName = (String)systemConf.get(SYSConst.CONF_DB_MYSQL) ;
            // 删除过时的need MTReport MTData中的数据
            List overDateMTList = this.getOverDateNeedReportMTList(gateway_DBName);
            if (null != overDateMTList && overDateMTList.size() > 0) {
                // save MsgStatusHistory
                if (DealOracleDBUtil.saveMsgHistoryStatus(this.name,overDateMTList, gateway_history)) {
                    // 删除need MTReport MTData临时表中的数据
                    Iterator itr = overDateMTList.iterator();
                    List overDateMsgIds = new ArrayList();
                    while (itr.hasNext()){
                        String msgid = ((MTStatusAndReportBean)itr.next()).getMsgId();
                        overDateMsgIds.add(msgid);
                    }
                    
                    if (!this.deleteDealed(overDateMsgIds, SQLConst.DELETE_NEED_REPORT_MTDATA, gateway_DBName)) {
                        log.error(" delete MTReportTemp need MTReport MTData failure ! ");
                    }
                } else {
                    log.error(" saveMsgStatusHistory for overDate need MTReport MTData failure ! ");
                }
            }
            
            // 删除过时的MTReportData中的数据
            List overDateReportList = this.getOverDateMTRportList(gateway_DBName);
            if (null != overDateReportList && overDateReportList.size() > 0) {
                int[] res = this.saveOverDateMTRport(overDateReportList, gateway_DBName);
                if (null != res && res.length == overDateReportList.size()) {
                    List overDateMsgIds = new ArrayList();
                    for (int i = 0; i < res.length; i++) {
                        // 对没有保存saveOverDateMTRport失败的，暂时不删除，等待转储处理
                        if (res[i] >= 1) {
                            String msgId = ((SubmitReportCmd) overDateReportList
                                    .get(i)).getMsgID();
                            overDateMsgIds.add(msgId);
                        }
                    }

                    // 删除need MTReport MTData临时表中的数据
                    if (!this.deleteDealed(overDateMsgIds, SQLConst.DELETE_MT_REPORT_DATA, gateway_DBName)) {
                        log.error(" delete  MTReport Data failure ! overDateMsgIds ：["
                                        + overDateMsgIds + "]");
                    }
                } else {
                    log.error(" saveOverDateMTRport for overDate need MTReport Data failure ! ");
                }
            }
            
            // 进入睡眠
            try {
                Thread.sleep(delay);
            } catch (InterruptedException ite) {
                log.error("InterruptedException in DealOverDateDataThread.run()!",
                                ite);
            }
        }
    }

    /**
     * 获得已经超时的需要report的MT数据
     * 
     * @return
     */
    private List getOverDateNeedReportMTList(String dbName) {
        List result = new ArrayList();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
//        int rs1[] = null;
//        PreparedStatement pstForThird = null;
        try {
            conn = DBConnectUtil.open(dbName);
            ps = conn
                    .prepareStatement(SQLConst.SELECT_OVERDATE_NEEDREPORT_MTDATA); 
            rs = ps.executeQuery();
           // pstForThird = conn.prepareStatement(SQLConst.SAVE_SKY3RD_STATUS);
            MTStatusAndReportBean mtStatusAndReport = null;
            while (rs.next()) {
                mtStatusAndReport = new MTStatusAndReportBean();
                mtStatusAndReport.setMsgId(rs.getString("MSGID"));
                mtStatusAndReport.setSubmitStatus(rs.getString("SUBMITSTATUS"));
                mtStatusAndReport.setSequenceID(rs.getString("SEQUENCEID"));
                mtStatusAndReport.setStype(rs.getInt("STYPE"));
                mtStatusAndReport.setServiceId(rs.getString("SERVICE_ID"));
                mtStatusAndReport.setOrgMobile(rs.getString("ORGMOBILE"));
                mtStatusAndReport.setOrgMobileType(rs.getInt("ORGMOBILETYPE"));
                mtStatusAndReport.setDestMobile(rs.getString("DEDESTMOBILE"));
                mtStatusAndReport
                        .setDestMobileType(rs.getInt("DESTMOBILETYPE"));
                mtStatusAndReport.setFeeMobile(rs.getString("FEEMOBILE"));
                mtStatusAndReport.setFeeMobileType(rs.getInt("FEEMOBILETYPE"));
                mtStatusAndReport.setFeeType(rs.getString("FEETYPE"));
                mtStatusAndReport.setFeeCode(rs.getInt("FEECODE"));
                mtStatusAndReport.setMsgContent(rs.getString("CONTENT"));
                mtStatusAndReport.setProvice(rs.getInt("PROVINCE"));
                mtStatusAndReport.setCity(rs.getInt("CITYNUMBER"));
                mtStatusAndReport.setCityName(rs.getString("CITYNAME"));
                mtStatusAndReport.setLinkID(rs.getString("RESERVED"));
                mtStatusAndReport.setCp(rs.getInt("CP"));
                mtStatusAndReport.setSubmitTime(rs.getString("SUBMITTIME"));
                mtStatusAndReport.setMsgReport(OVERDATE_ERROR_INFO);
                mtStatusAndReport.setDoneTime(rs.getString("SAVETIME"));
                mtStatusAndReport.setGateWayCode(rs.getString("GATEWAYCODE"));
                mtStatusAndReport.setMomtRelateID(rs.getString("MOMT_ID"));
                mtStatusAndReport.setSid(rs.getString("SID"));
                result.add(mtStatusAndReport);
            }
        } catch (SQLException sqle) {
            log.error("SQLException in DealOverDateNeedReportMTThread.getOverDateNeedRportMTList()!",
                            sqle);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException sqle) {
                log.error("release db connection unsuccessfully in DealOverDateNeedReportMTThread.getOverDateNeedRportMTList()!",
                                sqle);
            }
        }

        return result;
    }
    
    /**
     * 获得已经超时的MTReport数据
     * 
     * @return
     */
    private List getOverDateMTRportList(String dbName) {
        List result = new ArrayList();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBConnectUtil.open(dbName);
            ps = conn
                    .prepareStatement(SQLConst.SELECT_OVERDATE_MTREPORT_DATA);
            rs = ps.executeQuery();
            
            SubmitReportCmd submitReport = null;
            while (rs.next()) {
                submitReport = new SubmitReportCmd();
                submitReport.setMsgID(rs.getString("MSGID"));
                submitReport.setUserNumber(rs.getString("MOBILE"));
                submitReport.setUserNumberType(rs.getInt("MOBILETYPE"));
                submitReport.setReport(rs.getString("status"));
                submitReport.setDoneTime(rs.getString("SAVETIME"));
                result.add(submitReport);
            }
        } catch (SQLException sqle) {
            log.error("SQLException in DealOverDateNeedReportMTThread.getOverDateMTRportList()!",
                            sqle);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException sqle) {
                log.error("release db connection unsuccessfully in DealOverDateNeedReportMTThread.getOverDateMTRportList()!",
                                sqle);
            }
        }

        return result;
    }

    /**
     * delete dealed overDate need MTReport MTData
     * 
     * @param ids
     */
    private boolean deleteDealed(List msgIDs, String sSQL, String dbName) {
        boolean result = false;
        if (msgIDs == null || msgIDs.size() <= 0) {
            return false;
        }
        int num = msgIDs.size();
        Connection conn = null;
        PreparedStatement psForSendedMT = null;
        try {
            conn = DBConnectUtil.open(dbName);
            psForSendedMT = conn
                    .prepareStatement(sSQL);

            for (int i = 0; i < num; i++) {
                psForSendedMT.setString(1, (String) msgIDs.get(i));
                psForSendedMT.addBatch();
            }
            int[] res = psForSendedMT.executeBatch();

            if (res.length == num) {
                result = true;
                log.debug("delete needMTReport MTData OK! the number of dealing result are: "
                                + num);
            } else {
                result = false;
                log.error("delete needMTReport MTData failure !!!!!!");
            }

        } catch (SQLException e) {
            log.error("SQLException:", e);
        } catch (Exception e) {
            log.error("other Exception:", e);
        } finally {
            try {
                if (psForSendedMT != null) {
                    psForSendedMT.clearBatch();
                    psForSendedMT.close();
                }

                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                log.error("close:", e);
            }
        }
        return result;
    }
    
    /**
     * 转存需要没有匹配到MTReport
     * @param overDateList
     * @return
     */
    private int[] saveOverDateMTRport(List overDateList, String dbName){
        int[] result = null;
        Connection conn = null;
        PreparedStatement pst = null;
        try {
            conn = DBConnectUtil.open(dbName);
            pst = conn.prepareStatement(SQLConst.SAVE_OVERDATE_MTREPORT_DATA);
            Iterator itr = overDateList.iterator();
            while (itr.hasNext()) {
                SubmitReportCmd submitReport = (SubmitReportCmd) itr
                        .next();
                pst.setString(1, submitReport.getMsgID());// MSGID
                pst.setString(2, submitReport.getUserNumber());// orgmobile
                pst.setInt(3, submitReport.getUserNumberType());// orgmobiletype
                pst.setString(5, submitReport.getDoneTime());
                pst.setString(4, submitReport.getReport());
                pst.addBatch(); // 批处理
            }
            result = pst.executeBatch();

        } catch (SQLException sqle) {
            log.error("SQLException in "+name+".saveOverDateMTRport()!",
                            sqle);
        } finally {
            try {
                if (pst != null) {
                    pst.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException sqle) {
                log.error("release db connection unsuccessfully in "+name+".saveMsgHistoryStatus()!",
                                sqle);
            }
        }
        return result;
    }
    
}
